package t2h.activities;


import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import t2h.listsong.AccentRemover;
import t2h.valueobjects.SongVO;

import com.sun.lwuit.list.DefaultListModel;
import com.sun.lwuit.list.ListModel;

public class SearchSong {
	ListModel listmodel;
	static ListModel r = new DefaultListModel();
	//AccentRemover accentRemover = new AccentRemover();
	AccentRemover acc = new AccentRemover();
	
	
	public ListModel SearchSongByInput(final String inputString, ListModel inputList){	
		if(inputString.trim().equals(""))
			try {
				listmodel = new ReadXmlFile().getListKara();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		else
		listmodel = searchIn(inputList, new Matcher() {
			public boolean matches(SongVO t) {
				// TODO Auto-generated method stub
				String tempInput = acc.toRemoveVNese(inputString);
				tempInput = tempInput.toLowerCase();
				if(t.getId().indexOf(tempInput)!=-1)
					return true;
				else 
					if(acc.toRemoveVNese(t.getName()).indexOf(tempInput)!=-1)
						return true;
					else
						if(acc.toRemoveVNese(t.getAuthor()).indexOf(tempInput)!=-1)
							return true;
						else
							if(acc.toRemoveVNese(t.getLyric()).indexOf(tempInput)!=-1)
								return true;
				return false;
				//return t.getName().indexOf(inputString)==-1?false:true ;				
			}
		});
				
		return listmodel;
	}
	
	/*public ListModel SearchSongByInput(ListModel inputList){	
		
		listmodel = searchIn(inputList, new Matcher() {
			
			public boolean matches(SongVO t) {
				// TODO Auto-generated method stub
				return t.getName().equals("56660") ;
				
			}
		});
				
		return listmodel;
	}*/
	
	public static ListModel searchIn( ListModel list , Matcher m ) { 
	      if(r != null)
	    	  r = new DefaultListModel();
	      int sizeList = list.getSize();
	      for( int i = 0; i < sizeList; i++ ) { 
	          if( m.matches( (SongVO) list.getItemAt(0) ) ) { 
	              r.addItem( list.getItemAt(0) );
	          }
	          list.removeItem(0);
	      }
	      return r;
	  }
	
	/*public static ListModel searchIn( ListModel list , String s ) { 
        
		
	      for( int i = 0; i < list.getSize(); i++ ) { 
	    	  SongVO temp = (SongVO) list.getItemAt(i);
	          if(temp.getId().trim().equals(s.trim())) { 
	              r.addItem(temp);	              
	          }
	    	  
	      }
	      //r.addItem((SongVO) list.getItemAt(0));
	      return r;
	  }*/
}

interface Matcher { 
	  public boolean matches( SongVO t );
	}